package online.longzipeng.back.notify;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import online.longzipeng.back.pojo.dto.NotifyMessage;
import online.longzipeng.back.pojo.enums.MessageActionEnum;
import online.longzipeng.back.utils.NotifyUtils;

/**
 * @Author: lzp
 * @Description: 处理客户端响应的消息
 * @Date: Created in 10:02 2022/6/6
 */
public class ClientDataHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 用于记录和管理所有客户端的channel
     */
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override

    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 获取客户端所传输的消息  // JSON格式的消息
        String content = msg.text();
        // 客户端管道
        Channel channel = ctx.channel();
        if (ObjectUtil.isNotNull(content)) {
            // 转换消息对象
            NotifyMessage message = JSON.parseObject(content, NotifyMessage.class);
            if (message.getAction() == MessageActionEnum.CONNECT) {
                if (ObjectUtil.isNotNull(message.getContent())) {
                    // 将连接存入缓存
                    UserChanelRel.put( Long.parseLong(message.getContent()), channel);
                    NotifyUtils.pushMessage(channel, JSON.toJSONString(NotifyMessage
                            .builder()
                            .content("连接建立成功！！")
                            .build()));
                }
            }
            // 处理客户端的连接请求
            // 推送消息
        }
    }

}
